package com.cam.framework.utils;

import java.nio.charset.StandardCharsets;

public class CRCUtils {

    private static int crcCode(byte[] dataByteArray) {
        int crc_verify = 0xFFFF;
        for (byte b : dataByteArray) {
            crc_verify = (crc_verify >> 8) ^ b;
            for (int j = 0; j < 8; j ++) {
                int crc_test = crc_verify & 0x0001;
                crc_verify >>= 1;
                if (crc_test == 0x0001) {
                    crc_verify ^= 0xA001;
                }
            }
        }
        return crc_verify;
    }

    public static int getIntCrcCode(String dataString) {
        byte[] dataByteArray = dataString.getBytes(StandardCharsets.UTF_8);
        return crcCode(dataByteArray);
    }

    public static String getHexCrcCode(String dataString) {
        return String.format("%04x", getIntCrcCode(dataString)).toUpperCase();
    }

}
